﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
using System.ComponentModel.Composition;
using SonCa.SocialNetwork.Profiles.IPresenters;
using Core.BusinessLogic.Interfaces;
using Core.DataAccess;
using Core.Components;
using Core.Interfaces;
using Core.Common;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.UI;
using SonCa.SocialNetwork.Web;
using System.Web.Hosting;

namespace SonCa.SocialNetwork.Profiles.Presenters
{
    public class UploadAvatarPresenter
    {
        [Import]
        private IUserSession _userSession;
        [Import]
        private IProfileService _profileService;
        [Import]
        private IRedirector _redirector;
        [Import]
        private IFolderImgCoverService _folderImgCoverService;
        [Import]
        private IFileImgCoverService _fileImgCoverService;
        [Import]
        private IWebContext _webContext;
        [Import]
        private IWorkPlaceService _workPlaceService;
        [Import]
        private IAccountService _accountService;
        [Import]
        private ILevelService _levelService;

        private Core.DataAccess.Profile profile;
        private IUploadAvatar _view;

        public UploadAvatarPresenter()
        {
            MEFManager.Compose(this);
        }

        public void Init(IUploadAvatar View)
        {
            _view = View;
            if (_userSession.CurrentUser == null)
                _redirector.GoToLoginPage();
            int accountID = _userSession.CurrentUser.AccountID;
            if (_userSession.OtherAccountID > 0)
                accountID = _userSession.OtherAccountID;
            Account account = _accountService.GetAccountByID(accountID);

            if (account != null)
            {
                profile = account.Profile;
            }
            else
            {
                //_redirector.GoToErrorPage();
            }

            if (profile == null || profile.ProfileID < 0)
            {
                _redirector.GoToLoginPage();
            }
            else
            {
                WorkPlace workPlace = _workPlaceService.GetWorkPlaceByAccountID(accountID);

                _view.ShowAvatar(accountID);
                _view.ShowInfo(account, workPlace);
            }
        }

        public void StartNewAvatar()
        {
            _view.ShowUploadPanel();
        }

        public void Complete()
        {
            _view.CloseDialog();
            //_alertService.AddNewAvatarAlert();
            //_redirector.GoToProfilesProfile();
        }

        public void CropFile(Int32 X, Int32 Y, Int32 Width, Int32 Height)
        {
            //get byte array from profile
            byte[] imageBytes = profile.Avatar;
            //stuff this byte array into a memory stream
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                //write the memory stream out for use
                ms.Write(imageBytes, 0, imageBytes.Length);

                //stuff the memory stream into an image to work with
                System.Drawing.Image img = System.Drawing.Image.FromStream(ms, true);

                //create the destination (cropped) bitmap
                Bitmap bmpCropped = new Bitmap(200, 200);

                //create the graphics object to draw with
                Graphics g = Graphics.FromImage(bmpCropped);

                Rectangle rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);
                Rectangle rectCropArea = new Rectangle(X, Y, Width, Height);

                //draw the rectCropArea of the original image to the rectDestination of bmpCropped
                g.DrawImage(img, rectDestination, rectCropArea, GraphicsUnit.Pixel);

                //release system resources
                g.Dispose();

                MemoryStream stream = new MemoryStream();
                bmpCropped.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                Byte[] bytes = stream.ToArray();

                profile.Avatar = bytes;
                _profileService.SaveProfile(profile);
            }

            _view.ShowApprovePanel();
        }

        public void UploadFile(HttpPostedFile File, string page)
        {
            string extension = Path.GetExtension(File.FileName).ToLower();
            string mimetype;
            //byte[] uploadedImage = new byte[File.InputStream.Length];
            switch (extension)
            {
                case ".png":
                case ".jpg":
                case ".gif":
                    mimetype = File.ContentType;
                    break;

                default:
                    _view.ShowMessage("Chỉ chấp nhận file hình có đuôi .png, .jpg, and .gif!");
                    return;
            }

            if (File.ContentLength / 1000 < 3000)
            {
                ResizeImage(File);
                //File.InputStream.Read(uploadedImage, 0, uploadedImage.Length);
                //profile.Avatar = uploadedImage;
                //profile.AvatarMimeType = mimetype;
                //_profileService.SaveProfile(profile);
                //_view.ShowCropPanel();
                _redirector.GoToPage(page);
            }
            else
            {
                _view.ShowMessage("Hình bạn vừa upload có dung lượng lớn hơn 3MB. Bạn vui lòng upload file hình có dung lượng nhỏ hơn");
            }
        }

        private void ResizeImage(HttpPostedFile file)
        {
            // Create a bitmap of the content of the fileUpload control in memory
            Bitmap originalBMP = new Bitmap(file.InputStream);

            // Calculate the new image dimensions
            int origWidth = originalBMP.Width;
            int origHeight = originalBMP.Height;

            int newWidth = 200;
            int newHeight = 0;

            if (origWidth >= origHeight)
            {
                int sngRatio = origWidth / origHeight;
                newHeight = newWidth / sngRatio;
            }
            else if (origWidth < origHeight)
            {
                int sngRatio = origHeight / origWidth;
                newHeight = newWidth / sngRatio;
            }
            

            // Create a new bitmap which will hold the previous resized bitmap
            Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

            // Create a graphic based on the new bitmap
            Graphics oGraphics = Graphics.FromImage(newBMP);
            // Set the properties for the new graphic file
            oGraphics.SmoothingMode = SmoothingMode.AntiAlias; 
            oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // Draw the new graphic based on the resized bitmap
            oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
            // Save the new graphic file to the server
            //newBMP.Save(directory + "tn_" + filename);
            MemoryStream stream = new MemoryStream();            
            newBMP.Save(stream, ImageFormat.Jpeg);
            byte[] uploadImage = stream.ToArray();
            profile.Avatar = uploadImage;
            profile.AvatarMimeType = file.ContentType;
            // Once finished with the bitmap objects, we deallocate them.
            originalBMP.Dispose();
            newBMP.Dispose();
            oGraphics.Dispose();
            _profileService.SaveProfile(profile);
            _view.CloseDialog();
        }

        public string DisplayImgCover()
        {
            int accountID = _userSession.CurrentUser.AccountID;
            if (_userSession.OtherAccountID > 0)
                accountID = _userSession.OtherAccountID;
            FolderImgCover folder = _folderImgCoverService.GetFolderImgCoverByAccountID(accountID);
            if (folder != null)
            {
                //string folderName = Convert.ToDateTime(folder.CreateDate).Year.ToString() + Convert.ToDateTime(folder.CreateDate).Month.ToString();
                FileImgCover file = _fileImgCoverService.GetFileImgCoverByAccountID(accountID);
                if (file != null)
                {
                    string extension = System.IO.Path.GetExtension(file.FileName);
                    string fileSystemName = file.FileSystemName.ToString() + "__L" + extension;
                    string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,@"Files\Photos\" + fileSystemName);                    
                    if (System.IO.File.Exists(filePath))
                        return "~/Files/Photos/" + fileSystemName;
                    else
                        return "~/Images/PersonalCover/no_image.jpg";
                }
                else
                {
                    return "~/Images/PersonalCover/no_image.jpg";
                }
            }
            else
            {
                return "~/Images/PersonalCover/no_image.jpg";
            }
        }

        public int CheckAccountByAccountID()
        {
            return _accountService.CheckAccountByAccountID(_userSession.CurrentUser.AccountID, _userSession.OtherAccountID);
        }

        public string GetLevelByLevelID(int levelID)
        {
            return _levelService.GetLevelPathByLevelID(levelID);
        }
    }
}